package m4_routting;

import com.rabbitmq.client.*;

import java.io.IOException;
import java.util.Scanner;
import java.util.UUID;

public class Consumer {
    public static void main(String[] args) throws Exception{
        ConnectionFactory f = new ConnectionFactory();
        f.setHost("192.168.64.140");
        f.setPort(5672);
        f.setUsername("admin");
        f.setPassword("admin");
        //f.setVirtualHost("/刘沛霞");
        Channel c = f.newConnection().createChannel();

        //1.定义队列
        //随机命名,非持久,独占,自动删除
        String queue = UUID.randomUUID().toString();
        c.queueDeclare(
                queue,
                false,
                true,
                true,
                null);
        //2.定义交换机
        c.exchangeDeclare("direct_logs", BuiltinExchangeType.DIRECT);
        //3.绑定
        //用输入的绑定键进行绑定
        System.out.println("输入绑定键,用空格隔开");
        String s = new Scanner(System.in).nextLine();
        String[] a = s.split("\\s+");// ["aaa","bbb","ccc"]
        for (String key:a ){
            c.queueBind(queue,"direct_logs",key);
        }

        DeliverCallback deliverCallback = new DeliverCallback() {
            @Override
            public void handle(String consumerTag, Delivery message) throws IOException {
                String msg = new String(message.getBody());
                String key = message.getEnvelope().getRoutingKey();
                System.out.println("收到: "+msg+" - "+key);
            }
        };

        CancelCallback cancelCallback = new CancelCallback() {
            @Override
            public void handle(String consumerTag) throws IOException {
            }
        };

        //正常地消费数据
        c.basicConsume(
                queue,
                true,
                deliverCallback,
                cancelCallback);
    }
}
